import cv2
import glob
import os

def extract_frames_from_mp4(video_path, output_folder, frame_interval=10):
    cap = cv2.VideoCapture(video_path)
    frame_count = 0
    while True:
        ret, frame = cap.read()
        if not ret:
            break
        
        if frame_count % frame_interval == 0:
            output_path = f"{output_folder}/frame_{frame_count}.jpg"
            cv2.imwrite(output_path, frame)
        frame_count += 1
    cap.release()

def update_frames_from_mp4(video_path, output_folder):
    cap = cv2.VideoCapture(video_path)
    width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
    fps = cap.get(cv2.CAP_PROP_FPS)
    fourcc = cv2.VideoWriter_fourcc(*'mp4v')
    out = cv2.VideoWriter(output_folder+'\\..\\out.mp4',fourcc,fps,(width,height),False)
    while True:
        ret, frame = cap.read()
        if not ret:
            break
        frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        #frame = cv2.threshold(frame, 0, 255,)
        #frame = cv2.Canny(frame, 0, 10)
        out.write(frame)
    cap.release()
    out.release()

def test_frames_from_mp4(video_path, output_folder):
    cap = cv2.VideoCapture(video_path)
    while True:
        ret, frame = cap.read()
        if not ret:
            break
        frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        #_,frame = cv2.threshold(frame, 120, 100, cv2.THRESH_BINARY)
        frame = cv2.Canny(frame, 0, 100)
        cv2.imshow("test", frame)
        cv2.waitKey(10)

def preprocess_image():
    for file in glob.glob("deep_net\\video\\image\\*.jpg"):
        img = cv2.imread(file)
        img = cv2.Canny(img,0,100)
        cv2.imwrite("deep_net\\video\\canny\\"+os.path.basename(file), img)
        
    
video_file = "deep_net\\video\\49393662.mp4"
output_directory = "deep_net\\video"
#extract_frames_from_mp4(video_file, output_directory)
#update_frames_from_mp4(video_file, output_directory)
test_frames_from_mp4(video_file,output_directory)

#preprocess_image()